package com.management.department.teacherinfosystem.Utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 */
public class ExcelExportUtil {

    /**
     * 导出数据到Excel
     * @param data 数据列表
     * @param headers 表头映射 (字段名 -> 显示名称)
     * @param fileName 文件名
     * @return ResponseEntity包含Excel文件
     */
    public static ResponseEntity<byte[]> exportToExcel(List<?> data, Map<String, String> headers, String fileName) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("数据");
            
            // 创建表头样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            
            // 创建数据样式
            CellStyle dataStyle = createDataStyle(workbook);
            
            // 创建表头行
            Row headerRow = sheet.createRow(0);
            int colIndex = 0;
            for (String displayName : headers.values()) {
                Cell cell = headerRow.createCell(colIndex++);
                cell.setCellValue(displayName);
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            int rowIndex = 1;
            for (Object item : data) {
                Row dataRow = sheet.createRow(rowIndex++);
                colIndex = 0;
                
                for (String fieldName : headers.keySet()) {
                    Cell cell = dataRow.createCell(colIndex++);
                    Object value = getFieldValue(item, fieldName);
                    setCellValue(cell, value);
                    cell.setCellStyle(dataStyle);
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.size(); i++) {
                sheet.autoSizeColumn(i);
                // 设置最大宽度，避免过宽
                if (sheet.getColumnWidth(i) > 15000) {
                    sheet.setColumnWidth(i, 15000);
                }
            }
            
            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            byte[] excelBytes = outputStream.toByteArray();
            
            // 设置响应头
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            responseHeaders.setContentDispositionFormData("attachment", fileName + ".xlsx");
            
            return ResponseEntity.ok()
                    .headers(responseHeaders)
                    .body(excelBytes);
                    
        } catch (IOException e) {
            throw new RuntimeException("导出Excel失败", e);
        }
    }
    
    /**
     * 创建表头样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 设置背景色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        
        // 设置对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        return style;
    }
    
    /**
     * 创建数据样式
     */
    private static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 设置边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        // 设置字体
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        style.setFont(font);
        
        // 设置对齐
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        return style;
    }
    
    /**
     * 获取对象字段值
     */
    private static Object getFieldValue(Object obj, String fieldName) {
        try {
            // 支持嵌套字段，如 "user.name"
            String[] fieldParts = fieldName.split("\\.");
            Object currentObj = obj;
            
            for (String part : fieldParts) {
                if (currentObj == null) {
                    return null;
                }
                currentObj = getDirectFieldValue(currentObj, part);
            }
            
            return currentObj;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取直接字段值
     */
    private static Object getDirectFieldValue(Object obj, String fieldName) throws Exception {
        Class<?> clazz = obj.getClass();
        
        // 首先尝试getter方法
        try {
            String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method getter = clazz.getMethod(getterName);
            return getter.invoke(obj);
        } catch (Exception e) {
            // 如果getter方法不存在，尝试直接访问字段
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field.get(obj);
            } catch (Exception ex) {
                // 尝试父类字段
                Class<?> superClass = clazz.getSuperclass();
                if (superClass != null) {
                    try {
                        Field field = superClass.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        return field.get(obj);
                    } catch (Exception superEx) {
                        throw new Exception("无法获取字段值: " + fieldName);
                    }
                } else {
                    throw new Exception("无法获取字段值: " + fieldName);
                }
            }
        }
    }
    
    /**
     * 设置单元格值
     */
    private static void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
            return;
        }
        
        if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value ? "是" : "否");
        } else if (value instanceof LocalDateTime) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            cell.setCellValue(((LocalDateTime) value).format(formatter));
        } else if (value instanceof LocalDate) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            cell.setCellValue(((LocalDate) value).format(formatter));
        } else {
            cell.setCellValue(value.toString());
        }
    }
}
